package es.cea.agendatelefonica;

import java.io.IOException;
import java.util.List;

import javax.persistence.EntityManager;
import javax.persistence.EntityManagerFactory;
import javax.persistence.EntityTransaction;
import javax.persistence.Query;
import javax.servlet.ServletException;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

import com.google.appengine.api.datastore.Key;
import com.google.appengine.api.datastore.KeyFactory;


public class GuardarEdicionServlet extends HttpServlet {
	private static final long serialVersionUID = 1L;
       

    public GuardarEdicionServlet() {
        super();
        // TODO Auto-generated constructor stub
    }


	protected void doGet(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
		// TODO Auto-generated method stub
		
//		List<ContactoTel>contactos= (List)request.getSession().getServletContext().getAttribute(AgendaAtributos.contactos.toString());
		
		Long id = Long.parseLong(request.getParameter(AgendaAtributos.id.toString()));
		String nombre = request.getParameter(AgendaAtributos.nombre.toString());
		String telefono = request.getParameter(AgendaAtributos.telefono.toString());
		
		Key idKey = KeyFactory.createKey(ContactoTel.class.getSimpleName(), id);
		
		ContactoTel contacto = new ContactoTel(idKey,nombre,telefono);
		
		EntityManagerFactory entityManagerFactory = (EntityManagerFactory) request.getSession().getServletContext().getAttribute("emf");
		EntityManager entityManager = entityManagerFactory.createEntityManager();
		EntityTransaction transaction = entityManager.getTransaction();

//		Query query = entityManager.createQuery("SELECT from ContactoTel where id="+ request.getParameter(AgendaAtributos.id.toString())); 
//		ContactoTel contactoModificado = (ContactoTel) query.getSingleResult();
		
		transaction.begin();
//		contactoModificado = contacto;
		entityManager.merge(contacto);
		transaction.commit();
		
		request.getRequestDispatcher("contactoEditado.jsp").forward(request, response);
		
	}

	protected void doPost(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
		// TODO Auto-generated method stub
	}

}
